import copy
import datetime
import glob
import sys
import threading
import time as ti
import traceback
from concurrent.futures import ThreadPoolExecutor

import matplotlib
import pandas as pd
import matplotlib.dates as mdates
from PyQt5.QtCore import Qt, QDateTime
from PyQt5.QtWidgets import QFileDialog
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.dates import AutoDateLocator, DateFormatter, MinuteLocator, DateLocator
from pandas import Timestamp

from StressAna.Lib.Model import LabelsInit, Globalvariables
from StressAna.Lib.DataAna.AnkeDataAna import AnkeAna
from StressAna.Lib.DataAna.MonDataAna import MonAna
from StressAna.Lib.DataAna.TDDataAna import TDAna
from StressAna.Lib.ProcessAna import ProcessProc
from StressAna.UI.UI_Main import *

from StressAna.UI.UI_DataSyncTip import *

logger = Globalvariables.LOG.get_logger("main")

# warnings.filterwarnings('ignore')
matplotlib.use("Qt5Agg")
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # 设置默认字体
plt.rcParams["axes.unicode_minus"] = False  # 坐标轴正确显示正负号

'''
数据补数（取前一个值）
'''


def ana(data):
    for i, value in enumerate(data):
        if i > 0 and data[i] == 0:
            data[i] = data[i - 1]


'''
画布初始化
'''


class Figure_Canvas(FigureCanvas):
    def __init__(self, parent=None, width=13.5, height=8, dpi=100):
        self.fig = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
        FigureCanvas.__init__(self, self.fig)  # 初始化父类
        self.setParent(parent)
        self.axes = self.fig.add_subplot(111)

    def drawFig(self, data_list=None, data_list2=None, labels=None, title='对比分析'):
        if data_list is None:
            data_list = []
        if data_list2 is None:
            data_list2 = []
        if labels is None:
            labels = []

        data_legend = []
        for idata in data_list:
            line = self.axes.plot(idata[0], idata[1])
            data_legend.append(line[0])

        if data_list2:
            self.ax2 = self.axes.twinx()
            for idata in data_list2:
                line = self.ax2.plot(idata[0], idata[1], alpha=0.8, linestyle='--')
                data_legend.append(line[0])
            self.ax2.set_ylabel("摄氏度/℃")

        self.axes.set_title(title, pad=25)
        self.axes.set_xlabel("时间")
        self.axes.set_ylabel("Mpa")

        # locator = AutoDateLocator()
        if len(data_list[0][0]) <= 7 * 5760:
            locator = mdates.HourLocator(interval=4)
        elif len(data_list[0][0]) <= 14 * 5760:
            locator = mdates.HourLocator(interval=8)
        elif len(data_list[0][0]) <= 30 * 5760:
            locator = mdates.HourLocator(interval=12)
        else:
            locator = mdates.DayLocator()
        date_fmt = DateFormatter("%Y-%m-%d %H:%M")


        self.axes.xaxis.set_major_locator(locator)
        self.axes.xaxis.set_major_formatter(date_fmt)
        self.axes.tick_params(direction='in', length=6, width=2, labelsize=8)
        self.axes.xaxis.set_tick_params(labelrotation=90)
        self.axes.legend(data_legend, labels, loc=9, bbox_to_anchor=(0.5, -0.25), shadow=True, fancybox=True, ncol=4)

    def drawFigDis(self, data_list=None, data_list2=None, labels=None, title='对比分析'):
        if data_list is None:
            data_list = []
        if data_list2 is None:
            data_list2 = []
        if labels is None:
            labels = []

        data_legend = []
        for idata in data_list:
            line = self.axes.plot(idata[0], idata[1])
            data_legend.append(line[0])

        if data_list2:
            self.ax2 = self.axes.twinx()
            for idata in data_list2:
                line = self.ax2.plot(idata[0], idata[1], alpha=0.8, linestyle='--')
                data_legend.append(line[0])
            self.ax2.set_ylabel("摄氏度/℃")

        self.axes.set_title(title, pad=25)
        self.axes.set_xlabel("与工作面的距离/米")
        self.axes.set_ylabel("Mpa")

        self.axes.tick_params(direction='in', length=6, width=2, labelsize=12)
        self.axes.legend(data_legend, labels, loc=9, bbox_to_anchor=(0.5, -0.25), shadow=True, fancybox=True, ncol=4)


'''
数据对比类
'''


class ContrastMain(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.AkData_file_root_path = None
        self.TdData_file_root_path = None
        self.MonData_file_root_path = None
        self.setupUi(self)
        self.init()

    def init(self):
        self.TdData_file_root_path = r'D:\LK\TMV煤矿项目\应力数据\obsdata'
        self.AkData_file_root_path = r'D:\LK\TMV煤矿项目\应力数据\AK'
        self.MonData_file_root_path = r'D:\LK\TMV煤矿项目\应力数据\monidata'

        self.sID_TD_list = []
        self.sID_AK_list = []
        self.DF_ALL = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        self.DF_FILTER = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        self.DF_MON_ALL = pd.DataFrame(columns=['sID', 'time', 'temp', 'power'])
        self.FILTER_CONS = []
        self.ALL_FILTER_CONS = []
        self.TD_DATA_LIST = []
        self.SK_DATA_LIST = []

        self.sync_tip_dialog = None

        LabelsInit.sIDAttrInit()

        for i, dfi in Globalvariables.LABELS_DICT.groupby('length'):
            self.cb_CD.addItem(i)
        for i, dfi in Globalvariables.LABELS_DICT.groupby('wallThick'):
            self.cb_BH.addItem(i)
        for i, dfi in Globalvariables.LABELS_DICT.groupby('holeDepth'):
            self.cb_KS.addItem(i)
        for i, dfi in Globalvariables.LABELS_DICT.groupby('initialPress'):
            self.cb_CSY.addItem(i)

        now_day = ti.strftime("%Y-%m-%d", ti.localtime())
        self.dateEdit.setDateTime(QDateTime.fromString(f'{now_day}', "yyyy-MM-dd"))
        self.dateEdit_2.setDateTime(QDateTime.fromString(f'{now_day}', "yyyy-MM-dd"))
        self.DTEdit_start.setDateTime(QDateTime.fromString(f'{now_day} 00:00:00', "yyyy-MM-dd HH:mm:ss"))
        self.DTEdit_end.setDateTime(QDateTime.fromString(f'{now_day} 00:00:00', "yyyy-MM-dd HH:mm:ss"))
        self._init_sid_list()

    def _init_sid_list(self):
        for sID in Globalvariables.STATION_dict:
            if sID not in self.sID_TD_list:
                self.sID_TD_list.append(sID)
                newitem = QtWidgets.QListWidgetItem(f"{sID}:{LabelsInit.get_sIDAttr(f'{sID}')}")
                newitem.setCheckState(0)
                self.listWidget.addItem(newitem)
        for key, sID in Globalvariables.STATION_ANKE.items():
            if sID not in self.sID_AK_list:
                self.sID_AK_list.append(sID)
                newitem = QtWidgets.QListWidgetItem(f"{sID}-1:8M")
                newitem.setCheckState(False)
                self.listWidget_2.addItem(newitem)
                newitem = QtWidgets.QListWidgetItem(f"{sID}-2:14M")
                newitem.setCheckState(False)
                self.listWidget_2.addItem(newitem)

    '''
    导入泰德数据
    '''

    def load_single_td_data(self, file):
        try:
            tddata = TDAna(file)
            logger.info(file)
            self.TD_DATA_LIST.append(tddata.df)
        except:
            logger.error(traceback.format_exc())
            return

    def load_single_sk_data(self, file):
        try:
            aData = AnkeAna(file)
            for sID, dfi in aData.df.groupby('sID'):
                self.SK_DATA_LIST.append(dfi)
        except:
            logger.error(traceback.format_exc())
            return
        logger.info(file)

    def load_tddata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择泰德数据目录', self.TdData_file_root_path)
        if not Dir:
            return
        self.TdData_file_root_path = Dir
        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
        self.sync_tip_dialog.show()  # 以非模态对话框模式弹出
        self.statusbar.showMessage('正在加载泰德数据，请稍等...')

        self.load_tddata_thread = threading.Thread(target=self.load_tddata)
        self.load_tddata_thread.setDaemon(True)
        self.load_tddata_thread.start()

    def load_tddata(self):
        start_time = ti.time()
        dirs = glob.glob(f'{self.TdData_file_root_path}/**/*.txt', recursive=True)
        # threadPool = ThreadPoolExecutor(max_workers=5000, thread_name_prefix="load_data_")
        # for file in dirs:
        #     future = threadPool.submit(self.load_single_td_data, file)
        # threadPool.shutdown(wait=True)
        for file in dirs:
            self.load_single_td_data(file)
        # for df in self.TD_DATA_LIST:
        # self.DF_ALL = pd.concat([self.DF_ALL, df])
        if self.DF_ALL.empty:
            self.DF_ALL = pd.concat(self.TD_DATA_LIST)
        else:
            self.TD_DATA_LIST.append(self.DF_ALL)
            self.DF_ALL = pd.concat(self.TD_DATA_LIST)
        self.DF_ALL.reset_index(drop=True, inplace=True)

        if self.sync_tip_dialog:
            self.sync_tip_dialog.hide()
        end_time = ti.time()
        time_status = (
            f"完成时间:{ti.strftime('%H:%M:%S', ti.localtime())}, 处理时长:{(end_time - start_time) // 60}分{(end_time - start_time) % 60:.2f}秒")
        self.statusbar.showMessage(f'加载泰德数据结束，{time_status}')

    def load_skdata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择安科数据目录', self.AkData_file_root_path)
        if not Dir:
            return
        self.AkData_file_root_path = Dir
        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
        self.sync_tip_dialog.show()  # 以非模态对话框模式弹出
        self.statusbar.showMessage('正在加载思科赛德数据，请稍等...')

        load_skdata_thread = threading.Thread(target=self.load_skdata)
        load_skdata_thread.setDaemon(True)
        load_skdata_thread.start()

    def load_skdata(self):
        start_time = ti.time()
        dirs = glob.glob(f'{self.AkData_file_root_path}/**/*.xlsx', recursive=True)
        with ThreadPoolExecutor(max_workers=5000, thread_name_prefix="load_data_") as threadPool:
            for file in dirs:
                threadPool.submit(self.load_single_sk_data, file)
            threadPool.shutdown(wait=True)
        # for file in dirs:
        #     self.load_single_sk_data(file)
        for df in self.SK_DATA_LIST:
            self.DF_ALL = pd.concat([self.DF_ALL, df])
        self.DF_ALL.reset_index(drop=True, inplace=True)

        if self.sync_tip_dialog:
            self.sync_tip_dialog.hide()
        end_time = ti.time()
        time_status = (
            f"完成时间:{ti.strftime('%H:%M:%S', ti.localtime())}, 处理时长:{(end_time - start_time) // 60}分{(end_time - start_time) % 60:.2f}秒")
        self.statusbar.showMessage(f'加载泰德数据结束，{time_status}')

    '''
    导入泰德状态数据
    '''

    def load_mondata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择泰德状态数据目录', self.MonData_file_root_path)
        if not Dir:
            return
        self.MonData_file_root_path = Dir

        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
        self.sync_tip_dialog.show()  # 以非模态对话框模式弹出
        load_mondata_thread = threading.Thread(target=self.load_mondata)
        load_mondata_thread.setDaemon(True)
        load_mondata_thread.start()
        self.statusbar.showMessage('正在加载泰德状态数据，请稍等...')

    def load_mondata(self):
        start_time = ti.time()
        dirs = glob.glob(f'{self.MonData_file_root_path}/**/*.txt', recursive=True)
        self.MON_DATA_LIST = []
        for file in dirs:
            mondata = MonAna(file)
            self.MON_DATA_LIST.append(mondata.df)
        if self.DF_MON_ALL.empty:
            self.DF_MON_ALL = pd.concat(self.MON_DATA_LIST)
        else:
            self.MON_DATA_LIST.append(self.DF_MON_ALL)
            self.DF_MON_ALL = pd.concat(self.MON_DATA_LIST)
        self.DF_MON_ALL.reset_index(drop=True, inplace=True)

        if self.sync_tip_dialog:
            self.sync_tip_dialog.hide()
        self.statusbar.showMessage('加载泰德状态数据结束')
        end_time = ti.time()
        time_status = (
            f"完成时间:{ti.strftime('%H:%M:%S', ti.localtime())}, 处理时长:{(end_time - start_time) // 60}分{(end_time - start_time) % 60:.2f}秒")
        self.statusbar.showMessage(f'加载泰德数据结束，{time_status}')

    def get_cur_par(self):
        start_time_str = self.dateEdit.dateTime().date().toString("yyyy-MM-dd 00:00:00")
        end_time_str = self.dateEdit_2.dateTime().date().toString("yyyy-MM-dd 23:59:59")
        if start_time_str >= end_time_str:
            logger.error('开始时间不能大于结束时间！')
            return False, []
        sIDs = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                sIDs.append(self.listWidget.item(i).text())
        for i in range(self.listWidget_2.count()):
            if self.listWidget_2.item(i).checkState():
                sIDs.append(f"{self.listWidget_2.item(i).text()}:(思科赛德数据)")

        self.DF_FILTER = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        ids = [x.split(':')[0].split('-')[0] for x in sIDs]
        ids = list(set(ids))
        self.DF_FILTER = self.DF_ALL[
            (start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                self.DF_ALL['sID'].isin(ids))]
        return True, [start_time_str, end_time_str, sIDs]

    '''
    绘制波形
    '''

    def draw_slot(self):
        start_time = ti.time()
        flag, par_list = self.get_cur_par()
        if not flag:
            return
        start_time_str, end_time_str, sIDs = par_list
        if self.DF_FILTER.empty:
            self.statusbar.showMessage(f'{start_time_str}-{end_time_str}时间范围内无数据')
            return

        labels = []
        data_list = []
        data_list2 = []
        curDataList = []  # 开始压力和结束压力
        start_data = 0  # 找到开始的压力 默认0
        end_data = 0  # 找到结束的压力 默认0

        for item in sIDs:
            iName = item.split(':')[0]
            sID, chnNum = iName.split('-')
            _df = self.DF_FILTER[(self.DF_FILTER['sID'] == sID)]
            _df.loc[:, 'time'] = _df.loc[:, 'time'].astype('datetime64[ns]')
            _df = _df.drop_duplicates(['sID', 'time'], keep='first')
            _df = _df[_df[f'ch{chnNum}'] != -9999]  # 不显示-9999的数据
            x = _df['time'].to_list()
            y = _df[f'ch{chnNum}'].to_list()
            if self.cb_comple.checkState():
                ana(y)

            for i in y:
                if str(i) != 'nan':
                    start_data = i
                    break
            for i in y[::-1]:
                if str(i) != 'nan':
                    end_data = i
                    break

            # CtrX = []
            # CtrY = []
            # for i, value in enumerate(y):
            #     if value != -9999:
            #         CtrX.append(x[i])
            #         CtrY.append(value)
            data_list.append((x, y))
            curDataList.append((iName, start_data, end_data))
        if not data_list:
            logger.error(f'{start_time_str}-{end_time_str}时间范围内无数据')
            self.statusbar.showMessage(f'{start_time_str}-{end_time_str}时间范围内无数据')
            return

        if self.cb_temp.checkState():
            names_list = []
            for item in sIDs:
                iName = item.split(':')[0]
                sID, chnNum = iName.split('-')
                if sID in names_list:
                    continue
                names_list.append(sID)
                df_sel = self.DF_MON_ALL[
                    (start_time_str <= self.DF_MON_ALL['time']) & (self.DF_MON_ALL['time'] <= end_time_str) & (
                            self.DF_MON_ALL['sID'] == sID) & (
                        self.DF_MON_ALL['temp'])]
                if df_sel.empty:
                    continue
                df_sel.reset_index(drop=True, inplace=True)
                # df_sel.loc[:, 'time'] = df_sel.loc[:, 'time'].astype('datetime64[ns]')
                x = df_sel['time'].to_list()
                y = df_sel['temp'].to_list()
                data_list2.append((x, y))
                labels.append(f'{sID}-温度')
            sIDs.extend(labels)

        self.show_textBorwser(curDataList)
        self.setViewTail(data_list=data_list, data_list2=data_list2, labels=sIDs)

        self.cB_sidFilter.clear()
        for sid in sIDs:
            self.cB_sidFilter.addItem(sid)
        self.FILTER_CONS = []
        self.pb_draw_max.show()
        end_time = ti.time()
        time_status = (
            f"完成时间:{ti.strftime('%H:%M:%S', ti.localtime())}, 处理时长:{(end_time - start_time) // 60}分{(end_time - start_time) % 60:.2f}秒")
        self.statusbar.showMessage(f'绘制完成，{time_status}')

    def fliter_draw_slot(self):
        filter_start_time_str = self.DTEdit_start.dateTime().toPyDateTime()
        filter_end_time_str = self.DTEdit_end.dateTime().toPyDateTime()
        if filter_start_time_str >= filter_end_time_str:
            logger.error('开始时间不能大于结束时间！')
            return
        filter_sid_str = self.cB_sidFilter.currentText()
        filter_sid, filter_chnNum = filter_sid_str.split(':')[0].split('-')
        self.FILTER_CONS.append((filter_start_time_str, filter_end_time_str, filter_sid, filter_chnNum))
        self.filter_draw_proc()
        self.statusbar.showMessage('绘制完成！')

    def filter_draw_proc(self):
        flag, par_list = self.get_cur_par()
        if not flag:
            return
        start_time_str, end_time_str, sIDs = par_list
        labels = []
        data_list = []
        data_list2 = []
        curDataList = []  # 开始压力和结束压力
        start_data = 0  # 找到开始的压力 默认0
        end_data = 0  # 找到结束的压力 默认0

        for item in sIDs:
            iName = item.split(':')[0]
            sID, chnNum = iName.split('-')
            self.DF_FILTER.loc[:, 'time'] = self.DF_FILTER.loc[:, 'time'].astype('datetime64[ns]')
            _df = self.DF_FILTER[(self.DF_FILTER['sID'] == sID)]
            _df = _df.drop_duplicates(['sID', 'time'], keep='first')
            x = _df['time'].to_list()
            y = _df[f'ch{chnNum}'].to_list()
            if self.cb_comple.checkState():
                ana(y)

            # 不显示-9999的数据
            CtrX = []
            CtrY = []
            for i in range(len(x)):
                skip_flag = False
                if y[i] == -9999:
                    continue
                for cons in self.FILTER_CONS:
                    filter_start_time, filter_end_time, f_sid, f_chnNum = cons
                    if f_sid == sID and f_chnNum == chnNum and (filter_start_time <= x[i] <= filter_end_time):
                        skip_flag = True
                        break
                if skip_flag:
                    continue
                CtrX.append(x[i])
                CtrY.append(y[i])
            data_list.append((CtrX, CtrY))

            for i in CtrY:
                if str(i) != 'nan':
                    start_data = i
                    break
            for i in CtrY[::-1]:
                if str(i) != 'nan':
                    end_data = i
                    break
            curDataList.append((iName, start_data, end_data))
        if not data_list:
            logger.error(f'{start_time_str}-{end_time_str}时间范围内无数据')
            self.statusbar.showMessage(f'{start_time_str}-{end_time_str}时间范围内无数据')
            return

        if self.cb_temp.checkState():
            names_list = []
            for item in sIDs:
                iName = item.split(':')[0]
                sID, chnNum = iName.split('-')
                if sID in names_list:
                    continue
                names_list.append(sID)
                df_sel = self.DF_MON_ALL[
                    (start_time_str <= self.DF_MON_ALL['time']) & (self.DF_MON_ALL['time'] <= end_time_str) & (
                            self.DF_MON_ALL['sID'] == sID) & (
                        self.DF_MON_ALL['temp'])]
                if df_sel.empty:
                    continue
                df_sel.reset_index(drop=True, inplace=True)
                x = df_sel['time'].to_list()
                y = df_sel['temp'].to_list()
                data_list2.append((x, y))
                labels.append(f'{sID}-温度')
            sIDs.extend(labels)

        self.show_textBorwser(curDataList)
        self.setViewTail(data_list=data_list, data_list2=data_list2, labels=sIDs)

    def show_textBorwser(self, curDataList):
        # 显示当前波形开始压力值和结束压力值
        # self.textBrowser.setText('\n'.join(curDataList))
        self.textBrowser_2.clear()
        self.textBrowser_3.clear()
        self.textBrowser_4.clear()
        text_sids = []
        text_values1 = []
        text_values2 = []
        for row, row_values in enumerate(curDataList):
            text_sids.append(f'{row_values[0]}')
            text_values1.append(f'{row_values[1]}')
            text_values2.append(f'{row_values[2]}')
        self.textBrowser_2.setText('\n'.join(text_sids))
        self.textBrowser_3.setText('\n'.join(text_values1))
        self.textBrowser_4.setText('\n'.join(text_values2))

    '''
    绘制最大值波形
    '''

    def draw_max_slot(self):
        self.drawPic.setEnabled(False)
        flag, par_list = self.get_cur_par()
        if not flag:
            return
        start_time_str, end_time_str, sIDs = par_list

        data_list = []
        if 'date' not in self.DF_FILTER.columns:
            df_time = self.DF_FILTER['time'].astype('str')
            self.DF_FILTER.loc[:, 'date'] = df_time.apply(lambda x: x[:10])
        for item in sIDs:
            iName = item.split(':')[0]
            sID, chnNum = iName.split('-')
            df_sel = self.DF_FILTER[(self.DF_FILTER['sID'] == sID)]
            df_sel = df_sel[df_sel[f'ch{chnNum}'] != -9999]
            x = []
            y = []
            for idate, dfi in df_sel.groupby('date'):
                x.append(Timestamp(f"{idate} 00:00:00"))
                y.append(dfi[f'ch{chnNum}'].max())

            data_list.append((x, y))
            # data_list.append((x, y))
        self.setViewTail(data_list=data_list, labels=sIDs)
        self.statusbar.showMessage('绘制完成！')

    '''
    展示波形
    '''

    def setViewTail(self, data_list=None, data_list2=None, labels=None, dis_flag=False):
        # 图例
        labels = LabelsInit.labelsInit(labels)
        self.drawPic.setEnabled(False)

        self.fig_canvas = Figure_Canvas()  # 实例化类
        if not dis_flag:
            self.fig_canvas.drawFig(data_list=data_list, data_list2=data_list2, labels=labels,
                                    title=self.lineEdit.text())  # 调用类方法，作图
        else:
            self.fig_canvas.drawFigDis(data_list=data_list, data_list2=data_list2, labels=labels,
                                       title=self.lineEdit.text())  # 调用类方法，作图
        self.graphicscene = QtWidgets.QGraphicsScene()  # 创建一个QGraphicsScene，因为加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
        self.graphicscene.addWidget(self.fig_canvas)  # 把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到QGraphicsScene中的
        self.graphicsView.setScene(self.graphicscene)  # 把QGraphicsScene放入QGraphicsView
        self.graphicsView.show()  # 调用show方法呈现图形

        self.drawPic.setEnabled(True)

    def draw_finish_slot(self):
        self.drawPic.setEnabled(True)

    '''
    泰德数据全选
    '''

    def selall_slot1(self):
        for i in range(self.listWidget.count()):
            if not self.listWidget.item(i).checkState():
                self.listWidget.item(i).setCheckState(2)

    '''
    思科数据全选
    '''

    def selall_slot2(self):
        for i in range(self.listWidget_2.count()):
            if not self.listWidget_2.item(i).checkState():
                self.listWidget_2.item(i).setCheckState(2)

    '''
    泰德数据取消全选
    '''

    def selnoall_slot1(self):
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                self.listWidget.item(i).setCheckState(0)

    '''
    思科数据取消全选
    '''

    def selnoall_slot2(self):
        for i in range(self.listWidget_2.count()):
            if self.listWidget_2.item(i).checkState():
                self.listWidget_2.item(i).setCheckState(0)

    def sel_addr_slot(self):
        CD = self.cb_CD.currentText()
        BH = self.cb_BH.currentText()
        KS = self.cb_KS.currentText()
        CSY = self.cb_CSY.currentText()
        df = copy.deepcopy(Globalvariables.LABELS_DICT)
        if CD != '全部':
            df = df[(df['length'] == CD)]
        if BH != '全部':
            df = df[(df['wallThick'] == BH)]
        if KS != '全部':
            df = df[(df['holeDepth'] == KS)]
        if CSY != '全部':
            df = df[(df['initialPress'] == CSY)]
        # df_sel = df[(df['length']==CD) & (df['wallThick']==BH) & (df['holeDepth']==KS) & (df['initialPress']==CSY)]
        sta_list = df['sta'].unique().tolist()
        self.selnoall_slot1()
        for sta in sta_list:
            for i in range(self.listWidget.count()):
                if sta in self.listWidget.item(i).text():
                    self.listWidget.item(i).setCheckState(2)

    def re_sel_slot(self):
        pass

    def temp_save_slot(self):
        self.ALL_FILTER_CONS.extend(self.FILTER_CONS)

    def restore_slot(self):
        self.FILTER_CONS = self.ALL_FILTER_CONS
        self.filter_draw_proc()

    def filter_max_slot(self):
        self.drawPic.setEnabled(False)
        flag, par_list = self.get_cur_par()
        if not flag:
            return
        start_time_str, end_time_str, sIDs = par_list
        data_list = []
        for cons in self.ALL_FILTER_CONS:
            filter_start_time, filter_end_time, f_sid, f_chnNum = cons
            self.DF_FILTER.loc[
                (self.DF_FILTER['sID'] == f_sid) & (self.DF_FILTER['time'] >= filter_start_time) & (
                        self.DF_FILTER['time'] <= filter_end_time), f'ch{f_chnNum}'] = -9999
        if 'date' not in self.DF_FILTER.columns:
            df_time = self.DF_FILTER.loc[:, 'time'].astype('str')
            self.DF_FILTER.loc[:, 'date'] = df_time.apply(lambda x: x[:10])
        for item in sIDs:
            iName = item.split(':')[0]
            sID, chnNum = iName.split('-')
            df_sel = self.DF_FILTER[(self.DF_FILTER['sID'] == sID)]
            df_sel = df_sel[df_sel[f'ch{chnNum}'] != -9999]
            x = []
            y = []
            for idate, dfi in df_sel.groupby('date'):
                x.append(Timestamp(f"{idate} 00:00:00"))
                y.append(dfi[f'ch{chnNum}'].max())
            # 不显示-9999的数据
            # CtrX = []
            # CtrY = []
            # for i, value in enumerate(y):
            #     if value != -9999:
            #         CtrX.append(x[i])
            #         CtrY.append(value)
            data_list.append((x, y))
        self.setViewTail(data_list=data_list, labels=sIDs)
        self.statusbar.showMessage('绘制完成！')

    def draw_dis_slot(self):
        start_time = ti.time()
        sIDs = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                sIDs.append(self.listWidget.item(i).text())
        sids = [x.split(':')[0] for x in sIDs]

        data_list = []
        curDataList = []
        interval_dis = 50
        try:
            if self.le_dis.text():
                interval_dis = float(self.le_dis.text())
        except:
            logger.error('输入的进尺范围错误！')
        dev_dis_dates = ProcessProc.get_date_range(interval_dis)

        for dev, dates in dev_dis_dates.items():
            if dev in sids:
                iName = dev
                sID, chnNum = iName.split('-')

                cur_df = self.DF_ALL[
                    (min(dates) <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= (
                            datetime.datetime.strptime(max(dates), '%Y-%m-%d') + datetime.timedelta(
                        days=1)).strftime('%Y-%m-%d')) & (
                            self.DF_ALL['sID'] == sID)]
                if cur_df.empty:
                    logger.error(f'{dev}时间范围内无数据')
                    self.statusbar.showMessage(f'{dev}时间范围内无数据')
                    continue
                cur_df.loc[:, 'time'] = cur_df.loc[:, 'time'].astype('datetime64[ns]')
                cur_df = cur_df.drop_duplicates(['sID', 'time'], keep='first')
                _temp_series = cur_df['time'].apply(lambda x: x.strftime('%Y-%m-%d'))
                cur_df['date'] = _temp_series

                x = cur_df['time'].to_list()
                y = cur_df[f'ch{chnNum}'].to_list()
                if self.cb_comple.checkState():
                    ana(y)

                # 不显示-9999的数据
                CtrX = []
                CtrY = []
                # for i in range(len(x)):
                for i, _x in enumerate(x):
                    skip_flag = False
                    if y[i] == -9999:
                        continue
                    for cons in self.FILTER_CONS:
                        filter_start_time, filter_end_time, f_sid, f_chnNum = cons
                        if f_sid == sID and f_chnNum == chnNum and (filter_start_time <= _x <= filter_end_time):
                            skip_flag = True
                            break
                    if skip_flag:
                        continue
                    CtrX.append(_x)
                    CtrY.append(y[i])

                # 改为距离横坐标
                CtrXDis = []
                cur_date_list = cur_df['date'].unique().tolist()
                comp_num = [x for x in cur_date_list if x in dates]
                _finish_dis = len(comp_num) / len(dates) * interval_dis

                _inter = _finish_dis / len(CtrX)
                _rest_dis = interval_dis - _finish_dis
                for i in range(len(CtrX), 0, -1):
                    CtrXDis.append(-(i * _inter + _rest_dis))
                data_list.append((CtrXDis, CtrY))

                for i in CtrY:
                    if str(i) != 'nan':
                        start_data = i
                        break
                for i in CtrY[::-1]:
                    if str(i) != 'nan':
                        end_data = i
                        break
                curDataList.append((iName, start_data, end_data))
        if not data_list:
            logger.error(f'时间范围内无数据')
            self.statusbar.showMessage(f'时间范围内无数据')
            return
        self.show_textBorwser(curDataList)

        self.setViewTail(data_list=data_list, labels=sIDs, dis_flag=True)
        end_time = ti.time()
        time_status = (
            f"完成时间:{ti.strftime('%H:%M:%S', ti.localtime())}, 处理时长:{(end_time - start_time) // 60}分{(end_time - start_time) % 60:.2f}秒")
        self.statusbar.showMessage(f'绘制完成，{time_status}')


'''
数据同步提示框
'''


class SyncTipDialog(QtWidgets.QDialog, Ui_DataSyncTip):
    def __init__(self):
        super(SyncTipDialog, self).__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    Main = ContrastMain()
    Main.show()
    sys.exit(app.exec())
